const BaseController = require('../lib/RestController');

class CommentsClass extends BaseController {
  constructor(props) {
    super(props);
    this.table = 'comments';
  }
  async index() {
    const ctx = this.ctx, request = this.ctx.params,
      queries = this.ctx.queries,
      { mysql } = this.app,
      limit = queries.limit || 20,
      offset = queries.offset || 0,
      orders = queries.orders,
      hasLimit = !!queries.limit,
      columns = queries.columns;
    delete queries.limit;
    delete queries.offset;
    delete queries.orders;
    delete queries.columns;

    Object.keys(queries).forEach(v => { if (!queries[v]) delete queries[v] })

    const data = await mysql.query(`
    SELECT  
	comments.\`comment\`, 
	comments.id, 
	comments.course_id, 
	comments.user_id, 
	comments.parent_id, 
	comments.gmt_create, 
	comments.priority, 
	comments.del_flag, 
	course.title AS course, 
	users.nick_name AS nick_name
  FROM comments LEFT OUTER JOIN course ON comments.course_id = course.id
   LEFT OUTER JOIN users ON comments.user_id = users.id 
   ORDER BY gmt_create DESC 
   LIMIT ${limit} OFFSET ${offset}
   
   `)
    // const data = await mysql.select(this.table, Object.assign({
    //   where: queries,
    //   limit, // 返回数据量
    //   offset, // 数据偏移量
    // },
    //   columns ? { columns: JSON.parse(columns) } : {},
    //   orders ? { orders: JSON.parse(orders) } : {}
    // ));
    if (hasLimit) {
      const count = await mysql.count(this.table, queries)
      ctx.body = {
        status: 0,
        message: { data: data, count: count },
      };
      ctx.status = 200;
    } else {
      ctx.body = {
        status: 0,
        message: data,
      };
      ctx.status = 200;
    }
  }
}
module.exports = CommentsClass;
